import { message } from 'antd';
import html2canvas from 'html2canvas';
import { history } from 'umi'

import * as FileSaver from 'file-saver';

/**
 *@description 入职状态映射
 */
export const ENTRY_STATUS_MAP = {
    0: {
        name: '新员工确认入职'
    },
    1: {
        name: '招聘接收',
        tipText: '招聘接收',
        icon: 'iconjieshouxinyuangong1',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/recruitmentManager',
        code: 'office:personnel:progress:entry:preHr'
    },
    2: {
        name: '部门准备',
        icon: 'iconbumenzhunbei',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/employingDepartment',
        code: 'office:personnel:progress:entry:preDepartment'
    },
    3: {
        name: 'IT准备',
        icon: 'iconITzhunbei',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/itDepartment',
        code: 'office:personnel:progress:entry:webmaster'
    },
    4: {
        name: '行政准备',
        icon: 'iconhangzhengzhunbei',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/administration',
        code: 'office:personnel:progress:entry:administrative'
    },
    5: {
        name: '办理入职',
        tipText: '办理入职',
        icon: 'iconlistfunction_readyinterview_icon_default',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/hrLink',
        code: 'office:personnel:progress:entry:dealHr'
    },
    6: {
        name: '发放用品',
        icon: 'iconwuzifafang',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/officeGoods',
        code: 'office:personnel:progress:entry:release'
    },
    7: {
        name: '部门接收',
        tipText: '部门接收',
        icon: 'iconlistfunction_adddepartment_icon_default',
        url: '/office/personnelManagement/onboardAndLeave/entryManage/confirmReceipt',
        code: 'office:personnel:progress:entry:accept'
    },
    90: {
        name: '指派处理人',
        icon: null,
        url: null
    },
    91: {
        name: '修改入职时间',
        icon: null,
        url: null
    },
    100: {
        name: '完成入职',
        icon: 'iconyijianrenling1',
        url: null
    },
    101: {
        name: '终止入职',
        icon: 'iconzhongzhiruzhi1',
        url: null
    }
};

/**
 *@description 入职状态映射转换为数组，当前只转换key和其中的value中的name
 */
export const entryStatusMapToArray = () => {
    const arr = [];
    Object.entries(ENTRY_STATUS_MAP).forEach(([key, value]) => {
        arr.push({
            text: value?.name,
            value: key
        });
    });
    return arr;
};

/**
 * @description 字符串排序转换成数字
 * @param {string} sortstring 排序的字符串名称，值：ascend，descend
 * @returns {number} 升序：1；降序：2；不排序：0
 */
export const sortStringToNumber = sortstring => {
    if (!sortstring) return 0;
    switch (sortstring) {
        case 'ascend':
            return 1;
        case 'descend':
            return 2;

        default:
            return 0;
    }
};

/**
 * 材料类型映射
 */
export const MATERIAL = {
    EDUCATION: 'educationCertificate', // 学位证书
    RESIGNATION: 'resignationCertificate', // 离职证明
    ID_CARD: 'idCard', // 二代身份证
    UNDERGRADUATE: 'undergraduateCertificate', // (本科证书),
    XUE_XIN_NET: 'xuexinnetCertificate', // (学信网证明),
    MEDICAL_REPORT: 'medicalReport', // (入职体检报告),
    ID_PHOTO: 'idPhoto', // (2寸证件照),
    RELATED_QUALIFICATIONS: 'relatedQualifications', // (相关资格证书),
    SIGNED_CONTRACT: 'signedContract', // (已签订合同扫描件)
    CONTRACT_VERSION: 'contractVersion', // (合同模板)
    OTHER_CONTRACT: 'otherContract'
};

/**
 * 文件类型字典
 */
const fileDictionaries = [
    {
        fileType: 'image',
        fileExtension: ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'svg']
    },
    {
        fileType: 'office',
        fileExtension: [
            'doc',
            'docm',
            'docx',
            'dot',
            'dotm',
            'dotx',
            'csv',
            'xlam',
            'xls',
            'xlsb',
            'xlsm',
            'xlsx',
            'pot',
            'potm',
            'potx',
            'ppt',
            'pptx'
        ]
    },
    {
        fileType: 'pdf',
        fileExtension: ['pdf']
    }
];

/**
 *
 * 获取文件的扩展名
 */
export const getFileExt = file => file.substring(file.lastIndexOf('.') + 1).toLowerCase();

/**
 *
 * 根据文件名返回对应的文件类型
 */
export const getFileType = file => {
    const fileExtension = getFileExt(file);
    let fileType = '';
    // 注释eslint理由 需要使用for循环找到后直接返回节省遍历时间
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < fileDictionaries.length; i++) {
        if (fileDictionaries[i].fileExtension.includes(fileExtension)) {
            // eslint-disable-next-line prefer-destructuring
            fileType = fileDictionaries[i].fileType;
            break;
        }
    }

    return fileType;
};

/**
 * 判断来源是PC还是mobile
 */
export const getSource = () => {
    const ua = navigator.userAgent.toLowerCase();
    let btypeinfo = (ua.match(/firefox|chrome|safari|opera/g) || 'other')[0];
    if ((ua.match(/msie|trident/g) || [])[0]) {
        btypeinfo = 'msie';
    }
    let pc = '';
    let prefix = '';
    let plat = '';
    // 如果没有触摸事件 判定为pc
    const istocuh = 'ontouchstart' in window || ua.indexOf('touch') !== -1 || ua.indexOf('mobile') !== -1;
    if (istocuh) {
        if (ua.indexOf('ipad') !== -1) {
            pc = 'pad';
        } else if (ua.indexOf('mobile') !== -1) {
            pc = 'mobile';
        } else if (ua.indexOf('android') !== -1) {
            pc = 'androidpad';
        } else {
            pc = 'pc';
        }
    } else {
        pc = 'pc';
    }
    switch (btypeinfo) {
        case 'chrome':
        case 'safari':
        case 'mobile':
            prefix = 'webkit';
            break;
        case 'msie':
            prefix = 'ms';
            break;
        case 'firefox':
            prefix = 'moz';
            break;
        case 'opera':
            prefix = 'o';
            break;
        default:
            prefix = 'webkit';
            break;
    }
    plat = ua.indexOf('android') > 0 ? 'android' : navigator.platform.toLowerCase();
    return {
        // eslint-disable-next-line no-useless-escape
        version: (ua.match(/[\s\s]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1], // 版本
        plat, // 系统
        type: btypeinfo, // 浏览器
        pc,
        prefix, // 前缀
        isMobile: pc !== 'pc' // 是否是移动端
    };
};

/**
 * @description 手机端弹出遮罩提示长按保存图片
 * @param {String} src 图片的src地址，或者base64数据
 */
export const mobileImgSave = src => {
    const template = `<div id="mobileImgSavePop" style="position:fixed;width:100%;height:100%;z-index:1000;left:0;top:0;background:rgba(0,0,0,0.6);overflow:hidden;">
                            <p style="color:#fff;font-size:18px;margin-bottom:16px;margin-top:44px; text-align:center;">长按图片区域保存到手机相册</p>
                            <div style="padding:0 16px;background-color: #fff;padding:8px 4px 8px 0;margin: 0 19px;height: 82%;border-radius: 12px;">
                            <div style="max-width:750px;height:100%;border-radius: 12px;">

                                <div style="max-height:100%;margin:0; overflow-x:hidden;border-radius: 12px;" class="imgwrap">
                                    <img src='${src}' style="width:100%;border-radius: 12px;"/>
                                </div>
                            </div>
                        </div>
                    </div>`;
    let tempNode = document.createElement('div');
    tempNode.innerHTML = template;
    document.body.appendChild(tempNode.firstChild);
    const el = document.getElementById('mobileImgSavePop');
    el.addEventListener(
        'click',
        () => {
            document.getElementById('mobileImgSavePop').remove();
            tempNode = null;
        },
        false
    );
    el.querySelector('.imgwrap').addEventListener(
        'click',
        e => {
            e.stopPropagation();
        },
        false
    );
    window.addEventListener(
        'popstate',
        e => {
            e.stopPropagation();
            const els = document.getElementById('mobileImgSavePop');

            if (els) {
                els.click();
            }
        },
        false
    );
};

/**
 * @description 截图并下载图片，手机端采取的是弹窗长按保存图片，可以通过给dom添加data-hideinprint属性隐藏不显示的节点
 * @param {Object} dom dom对象
 * @param {String} filename 截图文件名称
 * @param {String} suffix 文件类型，默认png
 * @param {Booble} isShowTitle 是否将文件名显示在头部
 */
export const printScreenDown = (dom, filename, suffix, isShowTitle = false) => {
    if (dom) {
        if (isShowTitle === true) {
            const div = document.createElement('div');
            div.id = 'printTempTitleDiv';
            div.style.textAlign = 'center';
            div.style.fontSize = '24px';
            div.style.padding = '24px 0 16px';
            div.style.fontWeight = 600;
            const txt = document.createTextNode(filename.split('.')[0]);
            div.appendChild(txt);

            const { firstChild } = dom;
            dom.insertBefore(div, firstChild);
        }

        const hideDomArr = dom.querySelectorAll('[data-hideinprint]');
        // 隐藏不显示的id节点
        hideDomArr.forEach(item => {
            const el = item;
            el.setAttribute('data-display', el.style.display);
            el.style.display = 'none';
        });

        const width = dom.offsetWidth;
        const height = dom.offsetHeight;
        html2canvas(dom, {
            scale: 4,
            width,
            height
        }).then(canvas => {
            const uri = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream');
            if (getSource().isMobile) {
                mobileImgSave(canvas.toDataURL('image/png'));
            } else {
                FileSaver.saveAs(uri, `${filename}${suffix && suffix !== '' ? `.${suffix}` : '.png'}`);
            }
            const child = document.getElementById('printTempTitleDiv');
            if (child != null) {
                dom.removeChild(child);
            }
            // 显示被隐藏的节点
            hideDomArr.forEach(item => {
                const el = item;
                el.style.display = el.getAttribute('data-display');
            });
        });
    }
};

/**
 * 跳转至待入职
 * @param {String} error 错误提示
 * @param {Boolean} closeTab 是否关闭当前标签
 */
export const replaceToWaitEntry = (error = null) => {
    if (error) {
        message.error(error);
    }
    history.push({
        pathname: '/office/personnelManagement/onboardAndLeave/entryManage/waitEntry'
    });
};

/**
 *
 * @param {String} url 地址
 * @param {String} title 名称
 */
export const addFavorite = (url, title) => {
    try {
        window.external.addFavorite(url, title);
    } catch (e) {
        try {
            window.sidebar.addPanel(title, url, '');
        } catch (err) {
            message.warn(
                `抱歉，您所使用的浏览器无法完成此操作，请使用${
                    navigator.userAgent.toLowerCase().indexOf('mac') !== -1 ? 'Command/Cmd' : 'Ctrl'
                } + D 进行添加。`
            );
        }
    }
};
